import 'package:flutter_bilibili/http/core/dio_adapter.dart';
import 'package:flutter_bilibili/http/request/base_request.dart';

import 'hi_error.dart';
import 'hi_net_adapter.dart';
import 'mock_adapter.dart';

class HiNet{
  HiNet._();  // 构造函数
  static HiNet _instance = HiNet._(); // 饿汉式创建单例，防止null safe
  static HiNet getInstance() {
   return _instance;
  }
  Future fire(BaseRequest request) async {
    HiNetResponse response = await send(request);
    // var error;
    // try{
    //   response = await send(request);
    // } on HiNetError catch(e) {
    //   error = e;
    //   response = e.data;
    //   printLog(e.message);
    // } catch(e) {
    //   // 其它异常
    //   error = e;
    //   printLog(e);
    // }
    // if (response == null){
    //   printLog(error);
    // }
    var result = response.data;
    print("HiNet fire: $result");

    var status = response.statusCode;
    switch (status) {
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(result.toString(), data: result);
      default:
        throw HiNetError(status!, result.toString(), data: result);
    }
  }
  Future<dynamic> send<T>(BaseRequest request) async {
    // 使用Mock发送数据
    HiNetAdapter adapter = MockAdapter();
    // 使用Dio发送数据
    // HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);  // 通过adapter发送请求
  }
  void printLog(log) {
    print("hi_net:${log.toString()}");
  }
}